import { AuthService } from '@/apis/auth';
import { successMessage } from '@/helpers/antd/message';
import router from '@/routers';
import CommonPage from '@/routers/common-page';
import { createStorage } from '@/utils/storage-utils';
import { defineStore } from 'pinia';

const storageKeyPrefix = 'AUTHENTICATION_';
const storage = createStorage(storageKeyPrefix);

export const useAuthenticationStore = defineStore('authentication', () => {
  const accessToken = ref<string | null>(storage.get<string>('accessToken') || null);
  const captchaData = ref<AuthApiResp.Captcha>(null);

  const isLogin = computed(() => !!accessToken.value);

  async function fetchCaptchaAction() {
    const { data } = await AuthService.fetchCaptcha();
    captchaData.value = data;
  }

  async function loginAction(formData: AuthApiReq.AuthInfo, onSuccess?: () => Promise<void> | void) {
    try {
      const { data } = await AuthService.login(formData);
      storage.set('accessToken', data.accessToken);
      accessToken.value = data.accessToken;
      if (isLogin.value) {
        successMessage('登录成功');
        if (onSuccess) {
          await onSuccess();
        } else {
          await router.push(CommonPage.DASHBOARD);
        }
      }
    } catch {

    }
  }

  function clearAuthInfoAction() {
    accessToken.value = null;
    storage.clear();
  }

  return {
    accessToken,
    isLogin,
    captchaData,
    fetchCaptchaAction,
    loginAction,
    clearAuthInfoAction,
  };
});
